/*
 * Copyright 2010 Groupware.cc All right reserved. This software is the
 * confidential and proprietary information of Groupware.cc ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Groupware.cc.
 */
package com.rome.syncml.web.controller;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rome.syncml.bean.Contact;
import com.rome.syncml.bean.Telphone;
import com.rome.syncml.bean.VcardValue;
import com.rome.syncml.constant.Constant;
import com.rome.syncml.domain.User;
import com.rome.syncml.service.ContactService;
import com.rome.syncml.util.ContactUtil;

/**
 * 类ContactList.java的实现描述：TODO 类实现描述 
 * @author 11 2011-11-6 下午02:26:05
 */
@Controller
public class ContactController {

    @Resource
    private ContactService contractService;
    @RequestMapping(value="/contact/list")
    public ModelAndView list(HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("user");
        long userId = user.getId();
        Map<String,Object> map = contractService.query(userId, Constant.SOURCE_ID);
        ModelAndView view = new ModelAndView("contact/list");
        view.addObject("map", map);
        return view;
    }
    
    @RequestMapping(value="/contact")
    public ModelAndView home(HttpServletRequest request,String initial){
        User user = (User)request.getSession().getAttribute("user");
        long userId = user.getId();
        Map<String,Object> map = contractService.query(userId, Constant.SOURCE_ID);
        ModelAndView view = new ModelAndView("contact/home"); 
        List<Contact> list = (List<Contact>)map.get("all");
        StringWriter sw = new StringWriter();   

        view.addObject("map", map);
        view.addObject("list",list);
        String jsonStr = toJson(list);
        view.addObject("json",jsonStr);
        return view;
    }
    
    @RequestMapping(value="/edit")
    public ModelAndView edit(@RequestParam("id")long id){
        Contact contact = contractService.getContact(id);
        ModelAndView view = new ModelAndView("contact/edit");
        view.addObject("contact",contact);
        return view;
    }
    
    @RequestMapping(value="/contact/insert")
    public ModelAndView insert(){
        Contact contact = new Contact();
        contact.setId(0);
        ModelAndView view = new ModelAndView("contact/edit");
        view.addObject("contact",contact);
        return view;
    }
    
    @RequestMapping(value="/save")
    public String save(HttpServletRequest request,@ModelAttribute("contact")Contact contact,
                       @RequestParam("phone")String[] phones,@RequestParam(value="phoneTag",required=false)String[] phoneTags,
                       @RequestParam(value="url",required=false)String[] urls,@RequestParam(value="urlTag",required=false)String[] urlTags,
                       @RequestParam(value="email",required=false)String[] emails,@RequestParam(value="emailTag",required=false)String[] emailTag){
        User user = (User)request.getSession().getAttribute("user");
        long userId = user.getId();
        contact.setTelphones(buildValue(phones,phoneTags));
        contact.setEmails(buildValue(emails,emailTag));
        contact.setUrls(buildValue(urls,urlTags));
        if(contact.getId()==0){
            contractService.insert(contact, userId);
        }else{
            contractService.update(contact);
        }
        request.setAttribute("flg", true);
        return "redirect:contact";
    }
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(@RequestParam("id")long[] ids){
        contractService.delete(ids);
        return "success";
    }
    
    private List<VcardValue> buildValue(String[] values ,String[] tags){
        if(values!=null){
            List<VcardValue> list = new ArrayList<VcardValue>(values.length);
            for(int i=0 ; i<values.length ; i++){
                VcardValue card = new VcardValue();
                card.setValue(values[i]);
                if(tags!=null && i<tags.length){
                    card.setTag(tags[i]);
                }else{
                    card.setTag(VcardValue.defalutTag);
                }
                list.add(card);
            }
            return list;
        }
        return Collections.emptyList();
    }
    
    
    
    private String toJson(Object obj){
        StringWriter sw = new StringWriter();   
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(sw, obj);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sw.toString();
    }
}
